<?php

namespace App\Models\CacheModel\zl4;

use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;

class Zl4UserDataTypeStatus extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl4_user_data_type_status';

    protected $cacheModel = 'user.data_type_status';

    /**
     * 设置用户数据 状态信息
     * @param int $uid
     * @param string $key
     * @param int $status
     * @throws \Exception
     */
    public function setUserDataTypeStatus(int $uid, string $key, int $status)
    {
        $statusInfo = $this->getUserDataTypeStatus($uid, $key);

        if ($statusInfo)
        {   // 有过小红点 状态记录
            $this->where(['id' => $statusInfo['id']])->update(['status' => $status, 'update_time' => time()]);
        } else
        {   // 之前没有记录
            $this->insert([
                'uid' => $uid,
                'type' => $key,
                'status' => $status,
                'create_time' => time()
            ]);
        }
        // 删除 缓存
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache();
    }

    /**
     * 获取用户数据 状态信息
     * @param int $uid
     * @param string $key
     * @return array|null
     * @throws \Exception
     */
    public function getUserDataTypeStatus(int $uid, string $key)
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->getDataAndSet(function () use ($uid)
        {
            try
            {
                $data = $this->where(['uid' => $uid])->column('uid,type,status', 'id');

                $resData = [];
                foreach ($data as $id => $datum)
                {
                    $resData[$datum['type']] = json_encode([
                        'id' => (int)$datum['id'],
                        'type' => $datum['type'],
                        'status' => (int)$datum['status'],
                    ], JSON_UNESCAPED_UNICODE);
                }

                return $resData;
            }
            catch (\Exception $e)
            {
                Log::write('Zl4UserDataTypeStatus model => getUserDataTypeStatus()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
                return [];
            }
        }, [$key]);

        if ($data)
        {
            if (is_array($data))
            {
                return json_decode($data[$key], true);

            } else
            {
                return json_decode($data, true);
            }
        } else
        {
            return null;
        }
    }
}
